import React from 'react';
import { Form, Select, Input, DatePicker, TimePicker, message } from 'antd';
import moment from 'moment';
import cn from 'classnames';
import { useRequest } from '@/hooks';
import { InterviewerSchedule as Schedule } from '@/pages/Recruitment/containers';
import { getEmployeeInfoList } from '@/services/components/userform';
import { useInterviewWay } from '@/pages/RecruitEmail/hooks';

import { TALK_TYPE_LIST } from '../../constants';
import styles from './index.less';

const { Option } = Select;

// 面谈方式
export const INTERVIEW_WAY = {
    SITE: 1, // 现场
    VIDEO: 2, // 视频
    TEL: 3, // 电话
    WRITTEN: 4, // 笔试
    OTHER: 99 // 其它
};

export const interviewWayList = [
    {
        label: '现场',
        value: INTERVIEW_WAY.SITE
    },
    {
        label: '视频',
        value: INTERVIEW_WAY.VIDEO
    },
    {
        label: '电话',
        value: INTERVIEW_WAY.TEL
    },
    {
        label: '笔试',
        value: INTERVIEW_WAY.WRITTEN
    },
    {
        label: '其他',
        value: INTERVIEW_WAY.OTHER
    }
];

const DiscussArrange = ({
    form,
    data,
    typeList,
    wayList,
    interviewType,
    showInterviewType = true,
    rangeTitle = '新增日程'
}) => {
    const { getFieldDecorator } = form;
    const employeeRef = React.useRef(null);

    // 搜索人员
    const { data: employeeList, run: fetchEmployeeList, mutate: setEmployeeList } = useRequest(
        tagName =>
            getEmployeeInfoList({
                name: tagName,
                serviceStatus: [1, 2, 3, 4, 5, 6, 7]
            }),
        {
            debounceInterval: 500,
            manual: true,
            initialData: [],
            formatResult: res => {
                if (res) {
                    const { code, data: resData, msg } = res;
                    if (code === 10000) {
                        const map = {};
                        const finalResData = resData.filter(item => {
                            if (!map[item.employeeCode]) {
                                map[item.employeeCode] = true;
                                return true;
                            }
                            return false;
                        });
                        if (!employeeRef.current) {
                            employeeRef.current = finalResData;
                        }
                        return finalResData;
                    }
                    message.error(msg);
                }
                return undefined;
            }
        }
    );

    const handleEmployeeFocus = () => {
        if (employeeRef.current) {
            setEmployeeList(employeeRef.current);
        }
    };

    const handleSearch = _value => {
        if (_value) {
            fetchEmployeeList(_value.trim());
        }
    };

    const handleCheck = (v, type) => {
        form.setFieldsValue({
            [type]: form.getFieldValue(type)
        });
    };

    const handleOpenChange = (v, type) => {
        if (v) {
            return;
        }
        switch (type) {
            case 'interviewStartTime':
                if (!form.getFieldValue('interviewEndTime')) {
                    form.setFieldsValue({
                        interviewEndTime: form
                            .getFieldValue('interviewStartTime')
                            ?.clone()
                            .add(1, 'hours')
                    });
                }
                break;
            case 'interviewEndTime':
                if (!form.getFieldValue('interviewStartTime')) {
                    form.setFieldsValue({
                        interviewStartTime: form
                            .getFieldValue('interviewEndTime')
                            ?.clone()
                            .subtract(1, 'hours')
                    });
                }
                break;
            default:
                break;
        }
    };

    const renderOptions = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Option value={item.value} key={item.value}>
                    {item.label}
                </Option>
            ));
        }
        return null;
    };

    React.useEffect(() => {
        fetchEmployeeList();
    }, []);

    const renderInterviewType = () => {
        if (interviewType) {
            return TALK_TYPE_LIST.find(item => item.value === interviewType)?.label;
        }
        return getFieldDecorator('interviewType', {
            initialValue: data?.interviewType || undefined,
            rules: [
                {
                    required: true,
                    message: '面谈类型不能为空'
                }
            ]
        })(
            <Select
                placeholder="请选择面谈类型"
                allowClear
                getPopupContainer={triggerNode => triggerNode.parentElement}
            >
                {renderOptions(typeList || TALK_TYPE_LIST)}
            </Select>
        );
    };

    const [wayLabel] = useInterviewWay({ interviewWay: form.getFieldValue('interviewWay') });
    const initialLocation = data?.interviewLocation;

    // 这里挂载的时业务code
    const excludeInterviewCodes = Array.isArray(data?.interviewArrangeCode)
        ? data?.interviewArrangeCode
        : [data?.interviewArrangeCode];

    return (
        <>
            <Form className={styles.formWrap}>
                <div style={{ display: 'flex' }}>
                    {showInterviewType && (
                        <Form.Item label="面谈类型" style={{ width: '50%' }}>
                            {renderInterviewType()}
                        </Form.Item>
                    )}
                    <Form.Item label="面谈方式" style={{ width: '50%' }}>
                        {getFieldDecorator('interviewWay', {
                            initialValue: data?.interviewWay || undefined,
                            rules: [
                                {
                                    required: true,
                                    message: '面谈方式不能为空'
                                }
                            ]
                        })(
                            <Select
                                placeholder="请选择面谈方式"
                                allowClear
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                            >
                                {renderOptions(wayList || interviewWayList)}
                            </Select>
                        )}
                    </Form.Item>
                </div>

                <Form.Item label={wayLabel}>
                    {getFieldDecorator('interviewLocation', {
                        initialValue: initialLocation,
                        rules: [
                            {
                                required: form.getFieldValue('interviewWay') === 1,
                                message: '面谈地点不能为空'
                            }
                        ]
                    })(<Input placeholder={`请输入${wayLabel}`} allowClear maxLength={200} />)}
                </Form.Item>
                <Form.Item label="参与人">
                    {getFieldDecorator('interviewEmployeeCodeList', {
                        rules: [
                            {
                                required: true,
                                message: '参与人不能为空'
                            }
                        ],
                        initialValue: data?.interviewEmployeeCodeList
                    })(
                        <Select
                            mode="multiple"
                            style={{ width: '100%' }}
                            placeholder="请选择参与人"
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                            onFocus={handleEmployeeFocus}
                            onSearch={handleSearch}
                            filterOption={false}
                        >
                            {employeeList?.map(item => (
                                <Option value={item.employeeCode} key={item.employeeCode}>
                                    {item.employeeName}
                                </Option>
                            ))}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="面谈时间" required style={{ marginBottom: 0 }}>
                    <div style={{ display: 'flex' }}>
                        <Form.Item label="" colon={false} style={{ width: '100%', marginRight: 8 }}>
                            {getFieldDecorator('interviewDate', {
                                initialValue: data?.interviewStartTime ? moment(data?.interviewStartTime) : null,
                                rules: [
                                    {
                                        required: true,
                                        message: '面谈时间不能为空'
                                    }
                                ]
                            })(<DatePicker allowClear={false} placeholder="请选择日期" style={{ width: '100%' }} />)}
                        </Form.Item>
                        <Form.Item label="" colon={false} style={{ width: '100%', marginRight: 8 }}>
                            {getFieldDecorator('interviewStartTime', {
                                initialValue: data?.interviewStartTime ? moment(data?.interviewStartTime) : null,
                                rules: [
                                    {
                                        required: true,
                                        message: '开始时间不能为空'
                                    },
                                    {
                                        validator(rule, value, callback) {
                                            const endTime = form.getFieldValue('interviewEndTime');
                                            if (value && endTime && !endTime.isAfter(value)) {
                                                callback('请选择正确的开始时间');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <TimePicker
                                    allowClear={false}
                                    minuteStep={5}
                                    disabled={!form.getFieldValue('interviewDate')}
                                    format="HH:mm"
                                    placeholder="请选择开始时间"
                                    style={{ width: '100%' }}
                                    onChange={v => handleCheck(v, 'interviewEndTime')}
                                    onOpenChange={v => handleOpenChange(v, 'interviewStartTime')}
                                />
                            )}
                        </Form.Item>
                        ~
                        <Form.Item label="" colon={false} style={{ width: '100%', marginLeft: 8 }}>
                            {getFieldDecorator('interviewEndTime', {
                                initialValue: data?.interviewEndTime ? moment(data?.interviewEndTime) : null,
                                rules: [
                                    {
                                        required: true,
                                        message: '结束时间不能为空'
                                    },
                                    {
                                        validator(rule, value, callback) {
                                            const startTime = form.getFieldValue('interviewStartTime');
                                            if (value && startTime && !startTime.isBefore(value)) {
                                                callback('请选择正确的结束时间');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <TimePicker
                                    allowClear={false}
                                    minuteStep={5}
                                    disabled={!form.getFieldValue('interviewDate')}
                                    format="HH:mm"
                                    placeholder="请选择结束时间"
                                    style={{ width: '100%' }}
                                    onChange={v => handleCheck(v, 'interviewStartTime')}
                                    onOpenChange={v => handleOpenChange(v, 'interviewEndTime')}
                                />
                            )}
                        </Form.Item>
                    </div>
                </Form.Item>
            </Form>
            <Form className={cn(styles.formWrap2, styles.formWrap)}>
                <Form.Item label="参与人日程">
                    {getFieldDecorator('schedule', {
                        rules: [
                            {
                                validator(rule, value, callback) {
                                    if (!value) {
                                        callback('日程有冲突');
                                    } else {
                                        callback();
                                    }
                                }
                            }
                        ]
                    })(
                        <Schedule
                            rangeTitle={rangeTitle}
                            date={form.getFieldValue('interviewDate')}
                            timeRange={[
                                form.getFieldValue('interviewStartTime'),
                                form.getFieldValue('interviewEndTime')
                            ]}
                            onRangeChange={nextTimeRange => {
                                const [startTime, endTime] = nextTimeRange;
                                form.setFieldsValue({
                                    interviewDate: moment(startTime),
                                    interviewStartTime: moment(startTime),
                                    interviewEndTime: moment(endTime)
                                });
                            }}
                            excludeInterviewCodes={excludeInterviewCodes}
                            employeeCodes={form.getFieldValue('interviewEmployeeCodeList') || []}
                            height={400}
                        />
                    )}
                </Form.Item>
            </Form>
        </>
    );
};

export default DiscussArrange;
